package ml.kupin.search.service.impl;

import ml.kupin.search.dao.SearchDao;
import ml.kupin.search.service.SearchService;
import ml.kupin.common.vo.IndexItem;
import ml.kupin.common.vo.SearchResult;
import org.apache.solr.client.solrj.SolrQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 商品搜索Service
 * Created by 小柯(Allen Kerr) on 17.5.3 10:48.
 */
@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private SearchDao searchDao;

    @Override
    public SearchResult<IndexItem> search(String keyword, int page, int rows) throws Exception {
        //创建solrQuery对象
        SolrQuery solrQuery = new SolrQuery();
        //添加查询条件
        solrQuery.setQuery(keyword);
        solrQuery.set("df", "item_title");
        //这里再判断一下，比较稳妥
        if (page <= 0) page = 1;
        solrQuery.setStart((page - 1) * rows);
        solrQuery.setRows(rows);
        solrQuery.setHighlight(true);
        solrQuery.addHighlightField("item_title");
        solrQuery.setHighlightSimplePre("<span style='color:red'>");
        solrQuery.setHighlightSimplePost("</span>");
        //调用searchDao执行查询，获取查询结果
        SearchResult<IndexItem> searchResult = searchDao.search(solrQuery);
        //补全searchResult的属性
        searchResult.setPage(page);
        int totalPages = (int) Math.ceil(searchResult.getRecourdCount() * 1.0 / rows);
        searchResult.setTotalPages(totalPages);

        //==============测试异常处理================
//        int i = 1 / 0;
        //==============测试异常处理================

        //返回结果
        return searchResult;
    }
}
